package site.qjdb.controller;
import org.apache.tomcat.util.http.fileupload.FileUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import site.qjdb.constant.Info;
import site.qjdb.pojo.Goods;
import site.qjdb.pojo.User;
import site.qjdb.pojo.pagination.PageBean;
import site.qjdb.pojo.response.CommonResult;
import site.qjdb.pojo.response.ResponseCode;
import site.qjdb.service.CartService;
import site.qjdb.service.GoodsService;
import site.qjdb.service.UserService;
import site.qjdb.util.CommonUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/goods")
public class GoodsController {
	@Resource
	private GoodsService goodsService;
	@Resource
	private UserService userService;
	@Resource
	private CartService cartService;
	
	/**
	 * 	商品图片上传，缓存
	 * 	file：要上传的图片name，必传
	 * 
	 * */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String upload(@RequestParam MultipartFile file,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) throws IllegalStateException, IOException {
		
		boolean flag = true;
		long size = file.getSize();
		List<String> list = Arrays.asList(new String[] {
				".JPG",
				".PNG"
		});
		if(size > 1024 * 1024 * 2) {
			flag = false;
		} 
		String filename = file.getOriginalFilename();
		String fileFormat = filename.substring(filename.lastIndexOf('.'));
		if(!list.contains(fileFormat.toUpperCase())) {
			flag = false;
		}
		
		if(!flag) {
			return "redirect:/page/user/space/index.html/#/publish?e";
		} else {
			// 处理session和Cookie过期问题
			int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
			if(i == 0) {
				return "redirect:/page/user/login.html";
			}
			String realPath = session.getServletContext().getRealPath("");
			
			// 把路径保存到session中，file保存到临时文件夹下
			String tempFilePath = "/images/temp/" + CommonUtils.uuid() + fileFormat;
			String tempFP = (String)session.getAttribute(Info.TEMP_FILE_PATH);
			if(tempFP == null) {
				session.setAttribute(Info.TEMP_FILE_PATH, tempFilePath);
				file.transferTo(new File(realPath, tempFilePath));
				return "redirect:/page/user/space/index.html/#/publish?s";
			} else {
				int count = tempFP.split(";").length;
				if(count < 5) {
					session.setAttribute(Info.TEMP_FILE_PATH, tempFP + ";" + tempFilePath);
					file.transferTo(new File(realPath, tempFilePath));
					return "redirect:/page/user/space/index.html/#/publish?s";
				} else {
					return "redirect:/page/user/space/index.html/#/publish?c";
				}
			}
		}
	}
	
	/**
	 * 	获取session中缓存的图片路径
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/getTemp", method = RequestMethod.POST)
	public Object getTemp(HttpSession session) {
		String tempPath = (String)session.getAttribute(Info.TEMP_FILE_PATH);
		return new CommonResult<>(ResponseCode.SUCCESS, "success", tempPath);
	}
	
	/**
	 * 	移除已选择的图片
	 * imgPath：要移除的图片路径，必传
	 * @throws IOException 
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "removeImg", method=RequestMethod.POST)
	public Object removeImg(@RequestParam String imgPath,
			HttpSession session) throws IOException {
		// 若session过期则前端刷新页面重新填写商品信息
		String tempPath = (String)session.getAttribute(Info.TEMP_FILE_PATH);
		if(tempPath == null || "".equals(tempPath)) {
			return new CommonResult<>(ResponseCode.GOODS_STATE_EXPIRED);
		}
		imgPath = imgPath.substring(imgPath.indexOf("/qb") + 3);
		if(tempPath.indexOf(imgPath) != -1) {
			String[] tempPaths = tempPath.split(";");
			String newTempPath = "";
			for(int i = 0; i < tempPaths.length; i++) {
				if(tempPaths[i].equals(imgPath)) {
					continue;
				}
				newTempPath = newTempPath + tempPaths[i] + ";";
			}
			if(newTempPath.length() > 0) {
				// 若还有缓存图片则去除最后的分号
				newTempPath = newTempPath.substring(0, newTempPath.length() - 1);
			} else {
				// 若没有缓存图片了，则newTempPath为null
				newTempPath = null;
			}
			String applicationPath = session.getServletContext().getRealPath("").replaceAll("\\\\", "/");
			if(applicationPath.endsWith("/")) {
				applicationPath = applicationPath.substring(0, applicationPath.length() - 1);
			}
			File file = new File(applicationPath, imgPath );
			// 删除缓存文件
			FileUtils.forceDelete(file);
			// 更新session 
			session.setAttribute(Info.TEMP_FILE_PATH, newTempPath);
			return new CommonResult<>(ResponseCode.SUCCESS);
		} else {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
		
	}
	
	/**
	 * 	提交商品
	 * 	name：商品名称，必传
	 * 	price：商品价格，必传
	 * 	desc：商品详情，必传
	 * 	count：商品数量，必传
	 * 	label：商品标签，必传
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "submitProduct", method = RequestMethod.POST)
	public Object submitProduct(HttpSession session,
			@RequestParam String name,
			@RequestParam String price,
			@RequestParam String details,
			@RequestParam String count,
			@RequestParam String label) throws FileNotFoundException, IOException {
		
		// 若session过期则前端刷新页面重新填写商品信息
		String tempPath = (String)session.getAttribute(Info.TEMP_FILE_PATH);
		if(tempPath == null || "".equals(tempPath)) {
			return new CommonResult<>(ResponseCode.GOODS_STATE_EXPIRED);
		}
		// 判断用户个人信息是否完整
		User userSession = (User)session.getAttribute(Info.USER_SESSION);
		if("".equals(userSession.getNickname()) || 
				"".equals(userSession.getPhoneNumber()) || "".equals(userSession.getDepartment())) {
			return new CommonResult<>(ResponseCode.INCOMPLETE_USER_INFO);
		}
		name = URLDecoder.decode(URLEncoder.encode(name, "UTF-8"),"UTF-8");
		details = URLDecoder.decode(URLEncoder.encode(details, "UTF-8"),"UTF-8");
		label = URLDecoder.decode(URLEncoder.encode(label, "UTF-8"),"UTF-8");
		
		boolean flag = true;
		if(name.trim().equals("") || name.length() > 30) {
			flag = false;
		} else if (!price.matches("^(([1-9][0-9]*)|0)(\\.[0-9]+)?$") || price.length() > 11) {
			flag = false;
		} else if(details.trim().length() == 0 || details.length() > 500) {
			flag = false;
		} else if(!count.matches("^[1-9]\\d?")) {
			flag = false;
		}
		// 校验商品标签
		String[] labels = label.split(Info.GOODS_LABEL_SEPARATOR);
		if(labels == null || labels.length == 0) {
			flag = false;
		} else {
			for(String str : labels) {
				if(str.trim().length() == 0 || str.length() > 10) {
					flag = false;
					break;
				}
			}
		}
		
		if(!flag) {
			return new CommonResult<>(ResponseCode.INCORECT_FORMAT);
		}
		// 开始添加商品
		// 把图片从缓存地址移到/images/goods/里面
		String[] paths = tempPath.split(";");
		String applicationPath = session.getServletContext().getRealPath("").replaceAll("\\\\", "/");
		if(applicationPath.endsWith("/")) {
			applicationPath = applicationPath.substring(0, applicationPath.length() - 1);
		}
		String realPath = "";
		for(String path : paths) {
			path = applicationPath + path;
			File file = new File(path);
			if(file.exists()) {
				File dir = new File(applicationPath + "/images/goods");
				File[] files = dir.listFiles();
				String newDirPath = null;
				// 若goods文件夹下没有创建过文件夹
				if(files == null || files.length == 0) {
					newDirPath = dir.getAbsolutePath().replaceAll("\\\\", "/") + "/1/";
					new File(newDirPath).mkdir();
				} else {
					for(File f : files) {
						if(f.isDirectory()) {
							File[] _files = f.listFiles();
							if(_files != null && _files.length < Info.MAX_IMG_COUNT) {
								newDirPath = f.getAbsolutePath().replaceAll("\\\\", "/") + "/";
								break;
							}
						}
					}
					if(newDirPath == null) {
						newDirPath = dir.getAbsolutePath().replaceAll("\\\\", "/") + "/" + (files.length + 1) + "/";
						new File(newDirPath).mkdir();
					}
				}
				String endsName = path.substring(path.lastIndexOf("/") + 1);
				String newName = newDirPath + endsName;
				// 拷贝文件到新目录下
				InputStream in = new FileInputStream(file);
				OutputStream out = new FileOutputStream(newName);
				IOUtils.copy(in, out);
				in.close();
				out.close();
				// 把新图片路径加入到realPath中
				realPath = realPath + newName.substring(applicationPath.lastIndexOf("/qb")) + ";";
				// 删除缓存文件
				FileUtils.forceDelete(file);
			}
		}
		if(realPath.length() > 0) {
			realPath = realPath.substring(0, realPath.length() -1);
		}
		// 清空session里的缓存路径
		session.removeAttribute(Info.TEMP_FILE_PATH);
		Goods goods = new Goods();
		// 设置User
		User user = new User();
		user.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		goods.setUser(user);
		// 设置商品名称
		goods.setName(name);
		// 设置商品真实价格
		goods.setRealPrice(price);
		// 设置商品详情
		goods.setDetails(details);
		// 设置商品数量
		goods.setCount(Integer.parseInt(count));
		// 设置预约数量
		goods.setReservedCount(0);
		// 设置商品标签
		goods.setLabel(label);
		// 设置商品创建时间
		goods.setTime(new Date());
		// 设置是否为精选商品
		goods.setIsSelected(0);
		// 设置浏览量
		goods.setView(0);
		// 设置商品状态
		goods.setState(0);
		// 设置商品图片
		goods.setImgPath(realPath);
		goodsService.addGoods(goods);
		return new CommonResult<>(ResponseCode.SUCCESS);
	}
	
	/**
	 *	 查找用户发布的商品
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/myGoods", method = RequestMethod.POST)
	public Object myGoods(HttpSession session,
			HttpServletRequest request,
			HttpServletResponse response) {
		// 处理session和cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return new CommonResult<>(ResponseCode.UNLOGIN);
		}
		Goods goods = new Goods();
		User user = new User();
		user.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		goods.setUser(user);
		List<Goods> goodsList = goodsService.findGoodsAll(goods);
		return new CommonResult<>(ResponseCode.SUCCESS, goodsList);
	}
	
	/**
	 * 	商品详情
	 * 	gid：要查找的商品id，必传
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/{gid}/desc", method=RequestMethod.POST)
	public Object desc(@PathVariable String gid,
			HttpSession session) {
		Integer gidInteger =null;
		try {
			gidInteger = Integer.parseInt(gid);
		} catch(Exception e) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		// 查找商品，状态必须为1（通过）
//		synchronized(GoodsController.class) {
		Goods _goods = new Goods();
		_goods.setGid(gidInteger);
		_goods.setState(1);
		Goods newGoods = goodsService.findGoods(_goods);
		if(newGoods == null) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		//  浏览量加1
		Goods searchGoods = new Goods();
		searchGoods.setGid(newGoods.getGid());
		searchGoods.setView(newGoods.getView() + 1);
		goodsService.modifyGoods(searchGoods);
		newGoods.setView(searchGoods.getView());
		return new CommonResult<>(ResponseCode.SUCCESS, newGoods);
//		}
	}
	
	/**
	 * 	商品下架
	 * 	gid：商品id，必传
	 * 
	 * */
	@RequestMapping(value = "/{gid}/undercarriage", method=RequestMethod.GET)
	public String undercarriage(@PathVariable String gid,
			HttpServletRequest request,
			HttpSession session,
			HttpServletResponse response) {
		Integer gidInteger =null;
		try {
			gidInteger = Integer.parseInt(gid);
		} catch(Exception e) {
			return "redirect:/";
		}
		// 处理session和cookie过期问题
		int i = CommonUtils.handleSCExpire(request.getCookies(), session, response, userService);
		if(i == 0) {
			return "redirect:/page/user/login.html";
		}
		// 得到uid
		Goods goods = new Goods();
		User user = new User();
		user.setUid(((User)session.getAttribute(Info.USER_SESSION)).getUid());
		goods.setUser(user);
		goods.setGid(gidInteger);
		int j = goodsService.undercarriage(goods);
		if(j == 0 || j== 1) {
			return "redirect:/page/user/space/#/manage";
		} else {
			return "redirect:/page/user/space/#/manage?s";
		}
	}
	
	/**
	 * 	搜索商品
	 * 	keyword：搜索关键字，必传
	 * 	pc：当前页码，必传
	 * 	term：查询条件，必传
	 * 
	 * */
	@ResponseBody
	@RequestMapping(value = "/search", method = RequestMethod.POST)
	public Object search(@RequestParam String keyword,
			@RequestParam(value = "pc") String pcStr,
			@RequestParam String term,
			@RequestParam String price) {
		
		if("".equals(keyword.trim()) && !"3".equals(term)) {
			// 若关键字为空，且不是精选商品
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		}
		// 设置页码
		Integer pc = null;
		try {
			pc = Integer.parseInt(pcStr);
		} catch(Exception e) {
			// 默认是1
			pc = new Integer("1");
		}
		// 设置查询条件
		Goods goods = null;
		// 默认排序是精品、浏览量、留言量（以后再做）、发布时间
		String condition = "goods.isSelected desc,goods.view desc,goods.time desc";
		if("1".equals(term)) {
			// 新品
			condition = "goods.time desc,goods.isSelected desc,goods.view desc";
		} else if("2".equals(term)) {
			// 留言量
		} else if("3".equals(term)) {
			// 精选商品
			goods = new Goods();
			goods.setIsSelected(1);
		}
		// 设置价格
		String priceStr = null;
		if(price.indexOf("-") != -1 && price.split("-").length == 2) {
			String minPrice = price.split("-")[0];
			String maxPrice = price.split("-")[1];
			if(maxPrice.matches("^[1-9]\\d{0,9}$") && minPrice.matches("^[1-9]\\d{0,9}$")) {
				int max = Integer.parseInt(maxPrice);
				int min = Integer.parseInt(minPrice);
				if(min > max) {
					int temp = min;
					min = max;
					max = temp;
				}
				priceStr = min + "-" + max;
			}
		}
		// 设置一页共有10行数据
		Integer ps = 10;
		PageBean<Goods> pageBean = goodsService.searchGoodsAll(keyword, condition, pc, ps, goods, priceStr);
		if(pageBean == null) {
			return new CommonResult<>(ResponseCode.GOODS_NOT_FOUND);
		} else {
			return new CommonResult<>(ResponseCode.SUCCESS, pageBean);
		}
	}
	
	/**
	 * 	首页展示商品信息
	 * 
	 * */
	@ResponseBody
	@RequestMapping("/getIndexContents")
	public Object getIndexContents(HttpSession session) {
		return new CommonResult<>(ResponseCode.SUCCESS, session.getServletContext().getAttribute(Info.INDEX_CONTENT_APPLICATION));
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
